//
//  RefreshedTableViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/7/10.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

import UIKit
import Alamofire
class RefreshedTableViewController: BaseViewController,XYTableViewDelegate,RefreshedTableViewProtocol,UITextFieldDelegate,beginRefresh {
    
    var source: Array<JSON> = []
    
    var totalCount: Int = 0
    
    var page: Int = 1
    
    var tableView: RefreshedTableView = RefreshedTableView.init(frame: .zero, style: .plain)
    
    var cansearch = false
    
    var endDateField: UITextField {
        get{
            return self.searchHeader.endDateField
        }
    }
    
    override var names: Array<String>{
        
        get{
            return ["refresh","next"]
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    override func param(for name: String) -> Dictionary<String, Any> {
        if cansearch {
            let startTime = searchBar.text ?? ""
            let orgC = orgCode
            let endDate = endDateField.text ?? ""
            if name == "refresh" {
                var dic: [String: String] = [:]
                if startTime.count > 0 {
                    dic["startTime"] = startTime
                }
                if orgC.count > 0 {
                    dic["orgCode"] = orgC
                }
                if endDate.count > 0 {
                    dic["endDate"] = endDate + " 23:59:59"
                }
                return ["curPage":1,"pageSize":"20"] + dic
            } else if name == "next" {
                var dic: [String: String] = [:]
                if startTime.count > 0 {
                    dic["startTime"] = startTime
                }
                if orgC.count > 0 {
                    dic["orgCode"] = orgC
                }
                if endDate.count > 0 {
                    dic["endDate"] = endDate + " 23:59:59"
                }
                return ["curPage":String(page + 1),"pageSize":"20"] + dic
            } else {
                return ["":""]
            }
        } else {
            if name == "refresh" {
                return ["curPage":String(1),"pageSize":"20"]
            } else if name == "next" {
                return ["curPage":String(page + 1),"pageSize":"20"]
            } else {
                return ["":""]
            }
        }
    }
    
    override func path(for name: String) -> String {
        return ""
    }
    
    override func method(for name: String) -> NetMethod {
        return .get
    }
    
    override func success(for name: String) -> NetSuccess {
        
        func refreshSuccess(json: JSON)->Void{
            self.backView = nil
            self.tableView.endAnimation()
            if let success = json.contents?["success"]?.bool {
                if success == false {
                    self.alert(json.contents?["errorMsg"]?.rawString())
                    self.tableView.reloadData()
                    return
                }
            }
            
            guard let total = json.contents?["data"]?.contents?["total"]?.rawValue as? Int else {
                self.tableView.reloadData()
                self.tableView.tableFooterView = UIView()
                return
            }
            
            self.totalCount = total
            
            guard let list = json.contents?["data"]?.contents?["list"]?.array else {
                //刷新失败此时
                self.tableView.reloadData()
                self.tableView.tableFooterView = UIView()
                return
            }
            
            self.source = []
            
            for item in list {
                self.source.append(item)
            }
            
            self.tableView.tableFooterView = nil
            
            if self.source.count == 0 {
                self.tableView.tableFooterView = UIView()
            } else if self.source.count == self.totalCount {
                let footer = UILabel()
                footer.font = UIFont.systemFont(ofSize: 14)
                footer.text = "没有更多数据"
                footer.textAlignment = .center
                footer.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.view.width, height: 40))
                footer.backgroundColor = UIColor.dftBack
                footer.textColor = UIColor.hex("999999")
                self.tableView.tableFooterView = footer
            }
            self.tableView.reloadData()
        }
        
        func loadMoreSuccess(json: JSON)->Void{
            self.tableView.endAnimation()
            guard let total = json.contents?["data"]?.contents?["total"]?.rawValue as? Int else {
//                self.tableView.reloadData()
//                self.tableView.tableFooterView = UIView()
                return
            }
            
            self.totalCount = total
            
            guard let list = json.contents?["data"]?.contents?["list"]?.array else {
                //刷新失败此时
                self.tableView.reloadData()
                self.tableView.tableFooterView = UIView()
                return
            }
            
            if self.source.count > 0 {
                self.page += 1
            }
            
            for item in list {
                self.source.append(item)
            }
            
            if self.totalCount == self.source.count {
                //configfooter
                let footer = UILabel()
                footer.font = UIFont.systemFont(ofSize: 14)
                footer.text = "没有更多数据"
                footer.textAlignment = .center
                footer.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.view.width, height: 40))
                footer.backgroundColor = UIColor.dftBack
                footer.textColor = UIColor.hex("999999")
                self.tableView.tableFooterView = footer
            } else {
                self.tableView.tableFooterView = UIView()
            }
            self.tableView.reloadData()
        }
        
        return name == "refresh" ? refreshSuccess : loadMoreSuccess
    }
    
    override func strategy(for name: String) -> (Bool, String?, (() -> Void)?) {
        return (true, nil, nil)
    }
    
    func beginRefresh() {
        
        self.load(with: "refresh")
    }
    
    func loadNext() {
        self.load(with: "next")
    }

    private var _orgCode: String = User.orgCode
    
    var orgCode: String {
        set{
            _orgCode = newValue
        }
        get{
            return _orgCode
        }
    }
    
    var searchBar: UITextField {
        get{
            return searchHeader.beginDateField
        }
    }
    
    let datePicker = UIDatePicker(frame: CGRect.init(origin: CGPoint.zero, size: CGSize(width: UIScreen.main.bounds.size.width, height: 220)))
    
    let endPicker = UIDatePicker(frame: CGRect.init(origin: CGPoint.zero, size: CGSize(width: UIScreen.main.bounds.size.width, height: 220)))
    
    var companys: [JSON] = []
    
    var begindate: String {
        get{
            return datePicker.date.dateYearMonthDay
        }
    }
    
    override var shouldAutorotate: Bool{
        get{
            return true
        }
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        get{
            return UIInterfaceOrientationMask.portrait
        }
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        get{
            return UIInterfaceOrientation.portrait
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        
    }
    
    func orgalert()->UIAlertController{
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        
        for item in companys {
            let sheet = UIAlertAction.init(title: item.contents?["name"]?.rawString(), style: .default) { (action) in
                
                self.orgField.text = item.contents?["name"]?.rawString()
                
                self.orgCode = item.contents?["code"]?.rawString() ?? ""
                
                self.beginRefresh()
            }
            alert.addAction(sheet)
        }
        
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        
        alert.addAction(cancel)
        
        return alert
    }
    
    @objc func chooseorg()->Void{
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        
        for item in companys {
            let sheet = UIAlertAction.init(title: item.contents?["name"]?.rawString(), style: .default) { (action) in
                
                self.orgField.text = item.contents?["name"]?.rawString()
                
                self.orgCode = item.contents?["code"]?.rawString() ?? ""
                
                self.beginRefresh()
            }
            alert.addAction(sheet)
        }
        
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        
        alert.addAction(cancel)
        
        self.present(alert, animated: true, completion: nil)
    }
    
    var orgField: UITextField {
        get{
            return self.searchHeader.orgField
        }
    }
    
    @objc func clear()->Void{
        var owncompany = JSON()
        for item in companys {
            if item.contents?["code"]?.rawString() == User.orgCode {
                owncompany = item
                break
            }
        }
        self.orgField.text = owncompany.contents?["name"]?.rawString()
        self.orgCode = User.orgCode
        self.searchBar.text = ""
        self.endDateField.text = ""
        self.beginRefresh()
    }
    
    var netisactivity = true
    
    @objc func netshutdown()->Void{
        netisactivity = false
    }
    
    var backView: UIView?
    
    
    @objc func rfs()->Void{
        self.backView = nil
        self.tableView.backgroundView = nil
        self.beginRefresh()
    }
    
    @objc func netchanged()->Void{
        let state = NetManager.netstate
        switch state {
        case .notReachable:
            alert("无网络")
            break
        case .unknown:
            alert("无网络")
            break
        case .reachable(let type):
            switch type {
            case .ethernetOrWiFi:
                alert("当前正在使用WIFI网络")
                break
            case .wwan:
                alert("当前正在使用蜂窝网络")
                break
            }
        }
    }
    
    
    
    override func load(with name: String) -> Void {
        //得找一个有效策略
        
        let canReach = NetManager.isActive
        
        if canReach == false {
            if name.contains("refresh") {
                self.nothavenet()
                self.source = []
                self.tableView.endAnimation()
                self.tableView.reloadData()
            }
            self.failBlock(for: name)(NSError.init(domain: "NetError", code: -1, userInfo: ["NetReachability":false]))
        }
        
        let result = strategy(for: name)
        
        if result.0 == false {
            if result.2 != nil {
                result.2!();
            }else{
                self.alert(result.1)
            }
            return
        }
        self.beginLoading()
        switch self.method(for: name) {
        case .get:
            NetManager.get(self.path(for: name), self.param(for: name), suc: {(source) in
                self.endLoading()
                self.success(for: name)(source)
            }, fail: {(error) in
                self.endLoading()
                self.failBlock(for: name)(error)
            })
            break
        case .upload:
            let files = self.files(for: name)
            for file in files {
                NetManager.upload(self.path(for: name), self.param(for: name), [file], name: filename(for: name), suc: { (source) in
                    self.endLoading()
                    self.success(for: name)(source)
                }, fail: { (error) in
                    self.endLoading()
                    self.failBlock(for: name)(error)
                })
            }
        default:
            NetManager.post(self.path(for: name), self.param(for: name), suc: {(source) in
                self.endLoading()
                self.success(for: name)(source)
            }, fail: {(error) in
                self.endLoading()
                self.failBlock(for: name)(error)
            })
        }
    }
    
    let searchHeader = Bundle.main.loadNibNamed("SelectionHeaderView", owner: nil, options: nil)?[0] as! SelectionHeaderView
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //事件
        tableView.showsVerticalScrollIndicator = false
        searchHeader.delegate = self
        NotificationCenter.default.addObserver(self, selector: #selector(netchanged), name: NSNotification.Name.init(NETCHANGED), object: nil)
        orgField.delegate = self
        searchBar.delegate = self
        endDateField.delegate = self
        tableView.delegate = self as UITableViewDelegate
        
        tableView.dataSource = self as UITableViewDataSource
        
        tableView.refreshDelegate = self
        
        tableView.tableFooterView = UIView()
        
        self.view.addSubview(tableView)
        
        self.tableView.backgroundColor = UIColor.dftBack
        
        getorg()
        searchBar.backgroundColor = .white
        datePicker.locale = Locale.init(identifier: "zh_CN")
        datePicker.backgroundColor = UIColor.white
        datePicker.datePickerMode = .date
        
        let imgvew1 = UIImageView(frame: CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 8, height: 5)))
        imgvew1.image = UIImage.init(named: "icon_down")
        
        endDateField.backgroundColor = .white
        endPicker.locale = Locale.init(identifier: "zh_CN")
        endPicker.backgroundColor = UIColor.white
        endPicker.datePickerMode = .date
        NotificationCenter.default.addObserver(self, selector: #selector(beginRefresh), name: NSNotification.Name("RefreshDetail"), object: nil)
    }
    
    func getorg(){
        NetManager.get(GETORG, [:], suc: { (json) in
            if json.contents?["success"]?.bool == true {
                if let data = json.contents?["data"]?.array {
                    self.companys = data
                    if self.orgCode.count != 0 {
                        for item in self.companys {
                            if item.contents?["code"]?.rawString() == self.orgCode {
                                self.orgField.text = item.contents?["name"]?.rawString()
                                self.orgblock()
                                self.load(with: "refresh")
                            }
                        }
                    } else {
                        if User.isLeader {
                            let item = self.companys.filter({ (json) -> Bool in
                                return json.contents?["code"]?.rawString() == "x"
                            })
                            if item.count > 0 {
                                self.orgField.text = item[0].contents?["name"]?.rawString()
                                self.orgCode = item[0].contents?["code"]?.rawString() ?? ""
                                self.orgblock()
                                self.load(with: "refresh")
                            }
                        }
                    }
                }
            }
        }) { (error) in
            
        }
    }
    
    func orgblock()->Void{
        
    }
    
    func nothavenet() -> Void {
        self.tableView.backgroundView = nil
        backView = nil
        backView = UIView.init()
        self.tableView.backgroundView = backView
        let tray = UIView()
        backView?.addSubview(tray)
        tray.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(60)
            make.width.equalToSuperview().offset(-80)
            make.height.equalTo(240)
        }
        let imageView = UIImageView()
        tray.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview()
            make.width.equalTo(140)
            make.height.equalTo(140)
        }
        imageView.image = UIImage.init(named: "img_no_wifi")
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = UIColor.hex("999999")
        label.text = "请检查网络"
        label.textAlignment = .center
        label.size = label.text!.size(with: label.font)
        tray.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(imageView.snp.bottom).offset(0)
            make.width.equalTo(100)
            make.height.equalTo(20)
        }
        let reloadBtn = UIButton.init(type: .system)
        reloadBtn.backgroundColor = UIColor.mainColor
        reloadBtn.layer.cornerRadius = 3
        reloadBtn.setTitle("重新加载", for: .normal)
        reloadBtn.setTitleColor(UIColor.white, for: .normal)
        reloadBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        reloadBtn.addTarget(self, action: #selector(rfs), for: .touchUpInside)
        tray.addSubview(reloadBtn)
        reloadBtn.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalTo(tray.snp.bottom).offset(-55)
            make.width.equalToSuperview()
            make.height.equalTo(50)
        }
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        tableView.frame = self.view.bounds
        tableView.smileView.frame = CGRect.init(origin: CGPoint.init(x: self.view.width / 2 - 16, y: 0), size: CGSize(width: 32, height: 32))
        backView?.frame = self.tableView.bounds
        if (backView?.subviews.count ?? 0) > 0{
            if let subview = backView?.subviews[0] {
                self.tableView.backgroundView = backView
                subview.center = backView!.center
            }
        }
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            if  cansearch == true{
                return 40
            } else {
                return 0
            }
        default:
            return 0
        }
    }
    @objc override func endedit() {
        let header = self.searchHeader
        if let field = header.firstresponder {
            if let picker = header.currentpicker as? UIDatePicker {
                field.text = picker.date.dateLineStr
            }
        }
        self.searchHeader.endedit()
        self.view.endEditing(true)
        let begindate = self.datePicker.date
        let enddate = self.endPicker.date
        let interval = begindate.timeIntervalSince(enddate)
        if interval > 0 {
            self.searchBar.text = ""
            self.endDateField.text = ""
            self.beginRefresh()
        }
    }
    @objc override func canceledit() {
        self.view.endEditing(true)
    }
    
    @objc func searchAction()->Void{
        self.beginRefresh()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let tray = UIView()
        tray.backgroundColor = .white
        tray.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: UIScreen.main.bounds.size.width, height: 40))
        tray.addSubview(searchHeader)
        searchHeader.frame = CGRect.init(origin: .zero, size: CGSize.init(width: self.view.width - 10, height: 30))
        searchHeader.center = tray.center
        let line = UIView()
        line.backgroundColor = UIColor.hex("eeeeee")
        line.frame = CGRect.init(origin: CGPoint.init(x: 0, y: 39), size: CGSize.init(width: self.view.width, height: 1))
        tray.addSubview(line)
        return tray
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.source.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    var setyet = false
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let offY = scrollView.contentOffset.y
        
        let scroll = scrollView as! RefreshedTableView
        
        if offY <= 0 {
            scroll.smileView.scrollDidScroll()
        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        let scroll = scrollView as! RefreshedTableView
        
        scroll.smileView.scrollDidEndDraging()
        
        if scroll.contentSize.height <= scroll.frame.size.height {
            if scroll.contentOffset.y > 20 {
                scroll.refreshDelegate.loadNext?()
            }
        } else {
            if scroll.contentOffset.y > (scroll.contentSize.height - scroll.frame.size.height + 20) {
                if self.source.count < self.totalCount {
                    scroll.refreshDelegate.loadNext?()
                }
            }
        }
    }
}


func xy_noDataViewImage() -> UIImage {
    return UIImage(named: "img_no_data")!
}

func xy_noDataViewMessage() -> String {
    return "暂无数据"
}

func xy_noMoreDataTitle() -> String {
    return "没有更多数据"
}


